//
//  ViewController.m
//  项目换头像
//
//  Created by Zhao YanBin on 16/1/25.
//  Copyright © 2016年 zhaoyanbin. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic, retain)UIImageView *img;
@property(nonatomic, copy)NSString *lujing; //图片路径
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.img = [[UIImageView alloc] init];
    _img.frame = CGRectMake(50, 50, 100, 100);
    _img.center = CGPointMake(self.view.center.x, self.view.center.y);
    _img.layer.cornerRadius = 50;
    _img.clipsToBounds = YES;
    _img.userInteractionEnabled = YES;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];
    _img.image = [UIImage imageWithContentsOfFile:path];
    [self.view addSubview:_img];
    [_img release];
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    if ([userdefaults dataForKey:@"img"]) {
        [_img setImage:[UIImage imageWithData:[userdefaults dataForKey:@"img"]]];
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dianji)];
    [_img addGestureRecognizer:tap];
   
}

-(void)dianji
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    pickerImage.delegate = self;
    //是否可编辑  剪裁
    pickerImage.allowsEditing = YES;
    //跳转到相册页面
    [self presentViewController:pickerImage animated:YES completion:^{
        
    }];
    [pickerImage release];
}


//相册协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //将编辑后的图片保存在image中
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    //当图片不为空时显示图片并保存图片
    if (img != nil) {
        self.img.image = img;
        //以下是保存文件到沙河路径
        //把图片转成NSData类型的数据来保存文件
        NSData *data;
        if (UIImagePNGRepresentation(img)) {
            //返回为png图像
            data = UIImagePNGRepresentation(img);
        }else{
            data = UIImageJPEGRepresentation(img, 1.0);
        }
        //保存
        [[NSFileManager defaultManager] createFileAtPath:self.lujing contents:data attributes:nil];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:data forKey:@"img"];
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
